package com.imooc.dianping.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.dianping.common.BusinessException;

import com.imooc.dianping.common.EmBusinessError;
import com.imooc.dianping.request.PageInfo;
import com.imooc.dianping.dao.CategoryMapper;

import com.imooc.dianping.model.Category;

import com.imooc.dianping.request.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CategoryService extends ServiceImpl<CategoryMapper, Category> {

    @Autowired
    private CategoryMapper categoryMapper;

    @Transactional(rollbackFor = Exception.class)
    public void create(Category category) {
        if (categoryMapper.selectByName(category.getName()) != null) {
            throw new BusinessException(EmBusinessError.CATEGORY_DUP_FAIL);
        }
        save(category);
    }

    @Transactional(readOnly = true)
    public Category get(Integer id) {
        return categoryMapper.selectById(id);
    }

    @Transactional(readOnly = true)
    public PageInfo<Category> selectAll(PageQuery pageQuery) {
        Page<Category> page = new Page<>(pageQuery.getPage(), pageQuery.getSize());
        Page<Category> result = categoryMapper.selectPageOrderById(page);
        PageInfo<Category> pageInfo = new PageInfo<>();
        pageInfo.setList(result.getRecords());
        pageInfo.setTotal(result.getTotal());
        pageInfo.setPageNum(result.getCurrent());
        pageInfo.setPageSize(result.getSize());
        pageInfo.setPages(result.getPages());
        return pageInfo;
    }

}
